package store.wetravel.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by xinlong on 2017/10/13.
 */
public class TokenCache {

    private static Logger logger = LoggerFactory.getLogger(TokenCache.class);

    public static final String TOKEN_PREFIX = "token_";

    /**
     * initialCapacity(1000)：初始化缓存的容量为1000
     * maximumSize(10000)   ：设置缓存的最大容量，当缓存超过该值时guava会使用LRU（最少使用）算法来移除缓存项
     * expireAfterAccess(12, TimeUnit.HOURS)：缓存的有效期为12个小时
     */
    private static LoadingCache<String,String> localCache = CacheBuilder.newBuilder().initialCapacity(1000).maximumSize(10000).expireAfterAccess(12, TimeUnit.HOURS)
            .build(new CacheLoader<String, String>() {
                //默认数据加载实现，当调用get取值，如果key没有对应的值，就调用这个方法进行加载
                @Override
                public String load(String s) throws Exception {
                    //为了防止空指针异常（null.equals()），此处使用字符串的null
                    return "null";
                }
            });

    public static void SetKey(String key,String value){
        localCache.put(key,value);
    }

    public static void removeKey(String key){localCache.invalidate(key);}

    public static String getKey(String key){
        String value = null;
        try{
            value = localCache.get(key);
            if("null".equals(value)){
                return null;
            }
            return value;
        }catch (Exception e){
            logger.error("localCache get error",e);
        }
        return null;
    }

}
